import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, IsNeedBeginRefreshToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

import { constantRoutes } from '@/router/routes'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (!store.getters.deviceId) {
    await store.dispatch('app/getDeviceId')
    // console.log(store.getters.deviceId)
  }

  if (hasToken) {
    // 在有token的前提下，检查是否需要刷新token
    if (IsNeedBeginRefreshToken()) {
      console.log('需要刷新token')
      await store.dispatch('user/refreshToken').then(res => {
        // console.log(res)
      }).catch(() => {
        location.reload()
      })
    }
    if (!store.getters.menus || store.getters.menus.length <= 0) {
      // console.log('--后台刷新路由--')
      await store.dispatch('menu/getMenus').catch(error => {
        console.log('获取初始化菜单失败' + error)
        store.dispatch('user/resetToken')
        return Promise.reject(error)
      })
      // 重新组装新的路由
      const resRouters = [
        ...constantRoutes,
        ...store.getters.menus,
        {
          path: '*',
          redirect: '/404',
          hidden: true
        }
      ]
      // 这里动态添加路由，下面两行去掉任何一行，都不生效，正常写 router.addRoutes(resRouters) 这一行就行，但这里不起作用，原因待找
      router.options.routes = resRouters // 有可能 router.options.routes 不是相应shi
      router.addRoutes(resRouters)
      // 解决刷新路由变成空白界面的问题
      next({ ...to, replace: true })
    }
    // console.log(to)
    // 这里是为了如果显示了未读消息数，把未读消息数去掉
    if (to.meta && to.meta.msgNum) {
      to.meta.msgNum = 0
    }
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          await store.dispatch('user/getDepInfo')
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
          return Promise.reject(error)
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
